package com.gisterrier.client.components;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.TreeMap;

import com.common.shared.ClSelectionItem;
import com.common.shared.map.GisMapClickedObject;
import com.gisterrier.client.GisTerrier;
import com.gisterrier.shared.BuildingCustomer;
import com.gisterrier.shared.BuildingCustomerShort;
import com.gisterrier.shared.ClSelection;
import com.gisterrier.shared.ObjSelectionresult;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.ListGridEditEvent;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;

public class PMapBuildingSearch extends VLayout {

	private SelectItem siRegion;
	private SelectItem siSubRegion;
	private TextItem siCity;
	private TextItem siStreet;

	private TextItem tiBuildingNum;

	private ListGrid lgCustomes;
	private TreeMap<String, BuildingCustomerShort> mapCust = new TreeMap<String, BuildingCustomerShort>();
	private long buildingId;

	public PMapBuildingSearch() {
		super();
		setHeight100();
		setWidth100();
		DynamicForm form = new DynamicForm();
		form.setWidth100();
		// form.setBorder("1px solid red");
		form.setTitleAlign(Alignment.LEFT);

		siRegion = new SelectItem();
		siRegion.setTitle("Region");
		siRegion.setWidth("100%");

		siSubRegion = new SelectItem();
		siSubRegion.setTitle("Sub Region");
		siSubRegion.setWrapTitle(false);
		siSubRegion.setWidth("100%");

		siCity = new TextItem();
		siCity.setTitle("City");
		siCity.setWidth(200);
		siCity.setWidth("100%");

		siStreet = new TextItem();
		siStreet.setTitle("Street");
		siStreet.setWidth("100%");

		tiBuildingNum = new TextItem();
		tiBuildingNum.setTitle("Building Num");
		tiBuildingNum.setWrapTitle(false);
		tiBuildingNum.setWidth("100%");

		form.setLayoutAlign(Alignment.LEFT);
		form.setFields(siRegion, siSubRegion, siCity, siStreet, tiBuildingNum);
		this.addMember(form);

		ListGridField lgfCustId = new ListGridField("custId", "ID", 50);
		lgfCustId.setCanEdit(false);
		ListGridField lgfCustname = new ListGridField("custname", "ტიპი", 200);
		lgfCustname.setCanEdit(false);
		ListGridField lgfSelected = new ListGridField("Selected", "T", 20);
		lgfSelected.setType(ListGridFieldType.BOOLEAN);
		lgfSelected.setCanEdit(true);

		ListGridField lgfWas = new ListGridField("was", "T", 20);
		lgfSelected.setType(ListGridFieldType.BOOLEAN);
		lgfWas.setHidden(true);

		ListGridField lgfSerial = new ListGridField("serial");
		lgfSerial.setCanEdit(false);
		lgfSerial.setHidden(true);

		lgCustomes = new ListGrid() {
			@Override
			protected String getCellCSSText(ListGridRecord record, int rowNum,
					int colNum) {
				Object val = record.getAttribute("was");
				try {
					if (Boolean.parseBoolean(val.toString()))
						return "color:#d64949;";
				} catch (Exception e) {
					// TODO: handle exception
				}

				return super.getCellCSSText(record, rowNum, colNum);
			}
		};
		lgCustomes.setFields(lgfSelected, lgfCustId, lgfCustname, lgfSerial,
				lgfWas);
		lgCustomes.setCanEdit(true);
		lgCustomes.setEditEvent(ListGridEditEvent.CLICK);
		lgCustomes.setEditByCell(true);
		this.addMember(lgCustomes);

		HLayout dynamicForm = new HLayout();
		dynamicForm.setMembersMargin(10);

		Button bRemoveCustomers = new Button("Remove");
		bRemoveCustomers.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				removeCustomers();

			}
		});
		dynamicForm.setAlign(Alignment.RIGHT);
		dynamicForm.addMember(bRemoveCustomers);
		dynamicForm.setAutoHeight();
		this.addMember(dynamicForm);
	}

	private void removeCustomers() {
		ArrayList<BuildingCustomerShort> mapbuildCusts = new ArrayList<BuildingCustomerShort>();
		ListGridRecord[] lrs = lgCustomes.getRecords();
		for (ListGridRecord lr : lrs) {
			String serial = lr.getAttribute("serial");
			Boolean sel = lr.getAttributeAsBoolean("Selected");
			Boolean was = lr.getAttributeAsBoolean("was");

			if ((sel) /* || !sel && was */) {
				BuildingCustomerShort bc1 = mapCust.get(serial);
				if (bc1 != null
						&& (bc1.getBuilding_id() == buildingId || bc1
								.getBuilding_id() <= 0)) {
					BuildingCustomerShort bc = new BuildingCustomerShort();
					bc.setBuilding_id(buildingId);
					bc.setCusid(bc1.getCusid());
					mapbuildCusts.add(bc);
				}

			}
		}
		GisTerrier.gissTerrierService.insertMap_Customer_to_Building(
				mapbuildCusts, new AsyncCallback<ArrayList<Long>>() {

					@Override
					public void onSuccess(ArrayList<Long> result) {
						MainPanel.mainPanel.searchContainer
								.buildingCustomersChanged();
						refresh();

					}

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}
				});
	}

	private void setCustomers(ArrayList<BuildingCustomerShort> customerShorts) {
		if (customerShorts == null)
			customerShorts = new ArrayList<BuildingCustomerShort>();
		lgCustomes.setData(new ListGridRecord[] {});
		mapCust.clear();
		ArrayList<ListGridRecord> records = new ArrayList<ListGridRecord>();

		lgCustomes.setData(records.toArray(new ListGridRecord[] {}));
		for (BuildingCustomerShort cs : customerShorts) {
			String uId = HTMLPanel.createUniqueId();
			mapCust.put(uId, cs);
			ListGridRecord r = new ListGridRecord();
			r.setAttribute("custId", cs.getCusid());
			r.setAttribute("custname", cs.getCusname());
			r.setAttribute("Selected", false);
			r.setAttribute("was", cs.getBuilding_id() > 0);
			r.setAttribute("serial", uId);
			records.add(r);
		}
		lgCustomes.setData(records.toArray(new ListGridRecord[] {}));
	}

	public void refresh() {
		GisTerrier.gissTerrierService.getShortCustomersForBuilding(buildingId,
				new AsyncCallback<ArrayList<BuildingCustomerShort>>() {

					@Override
					public void onSuccess(
							ArrayList<BuildingCustomerShort> result) {
						setCustomers(result);

					}

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}
				});
	}

	public void setResult(BuildingCustomer bc, GisMapClickedObject clObj) {
		this.buildingId = clObj.getGid();
		TreeMap<Integer, ArrayList<ClSelectionItem>> result = bc
				.getAddressInfo();
		ObjSelectionresult selectionresult = bc.getSelectionresult();

		final long buildingId = clObj.getGid();
		final long raioni = clObj.getRaioni();
		final long regioni = clObj.getRegioni();
		final long cityid = selectionresult == null ? -1 : selectionresult
				.getCityid();
		final long streetid = selectionresult == null ? -1 : selectionresult
				.getStreetid();

		setSelectItems(siRegion, result.get(ClSelection.T_REGION));
		siRegion.setValue(regioni + "");
		siRegion.disable();
		setSelectItems(siSubRegion, result.get(ClSelection.T_SUBREGION));
		siSubRegion.setValue(raioni + "");
		siSubRegion.disable();
		siCity.setValue(clObj.getCity());
		siStreet.setValue(clObj.getSstreet());
		setCustomers(bc.getCustomerShorts());
		tiBuildingNum.setValue(clObj.getObj_text());
	}

	private void setSelectItems(SelectItem si, ArrayList<ClSelectionItem> items) {
		if (items == null) {
			items = new ArrayList<ClSelectionItem>();
		}
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("-1", "--");
		for (ClSelectionItem item : items) {
			map.put(item.getId() + "", item.getValue());
		}
		si.setValueMap(map);
		si.setValue("-1");
	}
}
